import logging

import boto3
import requests

# Configure logging
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)

# [profile Qa]
aws_access_key_id = "AKIASWZL2UIXMPQQ4NFT"
aws_secret_access_key = "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"
#
# [profile Prod]
# aws_access_key_id = "AKIAVGNWUKMQCF2NKKNR"
# aws_secret_access_key = "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"

# api服务密钥
# access_token = "AIzaSyCOTMbAcxEnt-Q1EuYZZPteSefQ7rl73To"

# AIzaSyC06NklsFspzAfNIm80RhPPeHpAyfagLB0

# 定义每页返回的项目数量
page_size = 500

# 定义初始化分页参数
start_key = None

# 总人数
total_count = 0

# 保存人数文件的地址
file_path = 'count.data'

# aws auth
table_name = 'oauth2-authentication-info'

aws_region = 'us-east-2'

session = boto3.Session(
    aws_access_key_id=aws_access_key_id,
    aws_secret_access_key=aws_secret_access_key,
    region_name=aws_region
)
dynamodb = session.client('dynamodb', region_name=aws_region)


def get_user_from_dynamodb():
    global start_key
    while True:
        if start_key:
            response = dynamodb.scan(
                TableName=table_name,
                Limit=page_size,
                ExclusiveStartKey=start_key
            )
        else:
            response = dynamodb.scan(
                TableName=table_name,
                Limit=page_size
            )
        tokens = response.get('Items', [])
        for token in tokens:
            user_id = token['user_id']['S']
            # 调用google request sync接口
            send_sync_request(user_id, token['code'])
        start_key = response.get('LastEvaluatedKey')
        if not start_key:
            logger.info("执行完成!")
            break


def send_sync_request(agent_user_id, code):
    # URL for Request Sync endpoint
    url = f"https://homegraph.googleapis.com/v1/devices:requestSync?key={access_token}"
    # Request body with device ID
    data = {
        "agentUserId": agent_user_id
    }

    # Send POST request
    response = requests.post(url, json=data)
    if response.status_code == 200:
        logger.info("Sync request sent successfully.")
    else:
        # 删除记录
        delete_record(code)
        logger.info(f"User:{agent_user_id} disconnect!")


def delete_record(code):
    dynamodb.delete_item(
        TableName=table_name,
        Key={'code': code}
    )


# 开始执行
if __name__ == "__main__":
    get_user_from_dynamodb()
